package com.gjl.app.view.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SessionFilter implements Filter{
	
	private static final String LOGOUT_URL = "logout_url";
	
	private static final String LOGIN_URL = "login_url";
	
	private static final String ADMIN = "admin";

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		UserService userService = UserServiceFactory.getUserService();
		HttpSession session = httpRequest.getSession(true);
		User user = userService.getCurrentUser();
		if (user != null && userService.isUserLoggedIn()) {
			String url = userService.createLogoutURL("/logout.action");
			session.setAttribute(LOGOUT_URL, url);
			session.setAttribute(ADMIN, userService.isUserAdmin());
		} else {
			session.setAttribute(LOGIN_URL, userService.createLoginURL("/login.action"));
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		
	}

}
